import { isValidIP, isValidPort } from "./utils.js";
const toast = document.querySelector("#toast");
const toastText = document.querySelector("#toast .toast-body");
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toast);
const localIP = document.querySelector("#local-ip");
const localPort = document.querySelector("#local-port");
// const targetIp = document.querySelector("#target-ip");
// const targetPort = document.querySelector("#target-port");
// 自动加载下位机地址
// targetIp.value = window.localStorage.getItem("targetIp");
// targetPort.value = window.localStorage.getItem("targetPort");
// const outputSwitch = document.querySelector("#output-switch");
const statusText = document.querySelector(".status-bar .status");
const progressDesc = document.querySelector("#progress-desc");
const progressPercent = document.querySelector("#progress-percent");
const progressBar = document.querySelector(".progress-bar");
const leftWall = document.querySelector(".left .photo-wall");
const rightWall = document.querySelector(".right .photo-wall");
const intervalInput = document.querySelector("#interval");
const lightInput = document.querySelector("#light");
// const fogInput = document.querySelector("#fog");
const noiseInput = document.querySelector("#noise");
const geoInput = document.querySelector("#geo");
const scaleInput = document.querySelector("#scale");
const resetBtn = document.querySelector("#reset-btn");
const genBtn = document.querySelector("#gen-btn");
// 是否收到任务
let isReady = false;
// WebSocket连接
fetch("/local-ip")
  .then((res) => res.json())
  .then((data) => {
    localIP.value = data.ip;
    localPort.value = 3003;
    const socket = new WebSocket(
      `ws://${localIP.value}:${localPort.value}/msg`
    );
    socket.addEventListener("message", wsHandler);
  });

function wsHandler(e) {
  console.log("Message from server ", e.data);
  // 命令处理
  const cmdArgs = e.data.split(" ");
  switch (cmdArgs[0]) {
    case "show":
      if (cmdArgs[1] === "initial") {
        fetchInit();
        statusText.classList.add("ready");
        statusText.textContent = "已收到卫星图像";
        progressDesc.textContent = "图像处理中...";
        runAndShow();
        progressPercent.textContent = "100%";
        progressBar.style.width = "100%";
        progressDesc.textContent = "图像处理完成";
        isReady = true;
        // if (outputSwitch.checked) {
        //   transImages();
        // }
      }
      break;
    case "tran":
      if (cmdArgs[1] !== "done") {
        progressDesc.textContent = "图像发送中...";
        progressPercent.textContent = `${cmdArgs[1]}%`;
        progressBar.style.width = `${cmdArgs[1]}%`;
      } else {
        progressDesc.textContent = "图像发送完成";
      }
      break;
  }
}

// 展示输入图片
function fetchInit() {
  while (leftWall.hasChildNodes()) {
    leftWall.removeChild(leftWall.firstChild);
  }
  fetch(`/initial-list?time=${new Date().getTime()}`)
    .then((res) => res.json())
    .then((data) => {
      for (let imgName of data) {
        const img = document.createElement("img");
        img.src = `/initial/${imgName}?time=${new Date().getTime()}`;
        leftWall.appendChild(img);
      }
    });
}

// 对图片采样加噪声并显示
async function runAndShow() {
  while (rightWall.hasChildNodes()) {
    rightWall.removeChild(rightWall.firstChild);
  }
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      interval: intervalInput.value,
      light: lightInput.value,
      // fog: fogInput.value,
      noise: noiseInput.value,
      geo: geoInput.value,
      scale: scaleInput.value,
    }),
  };
  const result = await fetch("/run-process", options).then((res) => res.json());
  if (result.code !== 0) {
    console.log(result.message);
    return;
  }
  const data = await fetch(`/processed-list?time=${new Date().getTime()}`).then(
    (res) => res.json()
  );
  for (let imgName of data) {
    const img = document.createElement("img");
    img.src = `/processed/${imgName}?time=${new Date().getTime()}`;
    rightWall.appendChild(img);
  }
}

// 向下位机传图片
function transImages() {
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ip: targetIp.value,
      port: targetPort.value,
    }),
  };
  fetch("/tran-image", options)
    .then((res) => res.json())
    .then((data) => {
      if (data.code === 0) {
        window.localStorage.setItem("targetIp", targetIp.value);
        window.localStorage.setItem("targetPort", targetPort.value);
      } else {
        toastText.textContent = data.message;
        toastBootstrap.show();
        // outputSwitch.checked = false;
        targetIp.removeAttribute("disabled");
        targetPort.removeAttribute("disabled");
      }
    });
}

// 自动发送开关
// outputSwitch.addEventListener("change", () => {
//   if (outputSwitch.checked) {
//     if (!isValidIP(targetIp.value)) {
//       toastText.textContent = "请输入正确的IP地址";
//       toastBootstrap.show();
//       outputSwitch.checked = false;
//       return;
//     }
//     if (!isValidPort(targetPort.value)) {
//       toastText.textContent = "请输入正确的端口号";
//       toastBootstrap.show();
//       outputSwitch.checked = false;
//       return;
//     }
//     targetIp.setAttribute("disabled", true);
//     targetPort.setAttribute("disabled", true);
//     resetBtn.setAttribute("disabled", true);
//     genBtn.setAttribute("disabled", true);
//     if (isReady) {
//       transImages();
//     }
//   } else {
//     targetIp.removeAttribute("disabled");
//     targetPort.removeAttribute("disabled");
//     resetBtn.removeAttribute("disabled");
//     genBtn.removeAttribute("disabled");
//   }
// });

// 重置参数
resetBtn.addEventListener("click", () => {
  resetBtn.setAttribute("disabled", true);
  intervalInput.value = 3;
  lightInput.value = 0;
  // fogInput.value = 0;
  noiseInput.value = 0;
  geoInput.value = 0;
  scaleInput.value = 0;
  resetBtn.removeAttribute("disabled");
});

// 手动更改参数
genBtn.addEventListener("click", async (e) => {
  if (!isReady) {
    toastText.textContent = "暂未收到卫星图像";
    toastBootstrap.show();
    return;
  }
  genBtn.setAttribute("disabled", true);
  await runAndShow();
  genBtn.removeAttribute("disabled");
});
